var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id"),ids="";
layui.use(['tableEdit',"selectInput"], function () {
    let layer = layui.layer,
        selectInput = layui.selectInput;

    //仓库信息
    let warehouseList = [];
    //货位
    let articleNoList = [];
    //客户信息
    let customerInfo = [];
    //供应商
    let materialSupplierList = [];
    //资源产品明细
    let detailData = [];

    $(document).ready(function () {

        //货位
        articleNoList = getdictionary(6, 38);

        $.ajax({
            url: "purchase/getFilterCustomer2List",
            async:false,
            success: function (res) {
                if (res.status == 200) {
                    materialSupplierList = res.data;
                    materialSupplierList.push({name: "无", code:"无"})
                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });

        getBaseData();

        table.reload('productinformationtableid',{data : detailData});
    })

    function getBaseData(){
        //获取资源仓库信息
        $.ajax({
            url:"resourceSamples/getResourceWarehouseInfo",
            async:false,
            success:function(data){
                if(data.status == 200){
                    warehouseList = data.data;
                    for(let i in data.data){
                        $('#warehouseId').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    form.render('select');
                }
            }
        });

        //获取详情信息
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(id),
            url:"resourceSamples/detail",
            async:false,
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    $("#id").val(res.data.id);
                    $("#billNo").val(res.data.billNo);
                    $("#newBillNo").val(res.data.billNo);
                    $('#warehouseId').val(res.data.warehouseId);
                    $("#warehouseName").val(res.data.warehouseName);
                    $("#createDate").val(res.data.createDate);
                    $("#operator").val(res.data.operator);
                    //setCustomerInfo(res.data.customerName);
                    //$('#customerCode').val(res.data.customerCode);
                    $('#customerName').val(res.data.customerName);
                    $("#typeStr").val(res.data.typeStr);
                    $("#memo").val(res.data.memo);

                    //产品列表信息
                    detailData = res.data.detailList;
                    for(let j in detailData){
                        let num = GenNonDuplicateID(3) + (parseInt(j)+1);
                        detailData[j].tempId = num;
                    }
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }

    function setCustomerInfo(initData) {
        let ins = selectInput.render({
            elem: '#customerSelect',
            name: 'customerSelect',
            initValue: initData,
            hasSelectIcon: true,
            placeholder: '请输入名称',
            data: [],
        })

        //监听输入
        ins.on('itemInput(customerSelect)', function (obj) {
            let tempData = [];
            //获取客户信息
            getCustomerInfo(obj.value);
            if(customerInfo){
                for (let i in customerInfo) {
                    customerInfo[i]["value"] = customerInfo[i].code;
                    tempData.push(customerInfo[i]);
                }
            }else {
                let tmp = {
                    name: "未找到",
                    value:""
                }
                tempData.push(tmp);
            }
            ins.addSelect(tempData)
        })

        // 监听select 选择事件
        ins.on('itemSelect(customerSelect)', function (obj) {
            let code = obj.data;
            let name = obj.textContent;
            $("#customerCode").val(code);
            $("#customerName").val(name);
        });
    }

    /**
     * 获取客户信息
     * @param name 客户名称
     */
    function getCustomerInfo(name) {
        $.ajax({
            url: "basicInformation/getCustomerOfSelf?info=" + name,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    customerInfo = res.data.customerInfo;
                }else {
                    customerInfo = [];
                }
            }
        })
        return;
    }

    //监听仓库下拉框
    form.on('select(warehouseId)', function (data) {
        if(data.value === ""){
            $("#warehouseName").val("");
            return;
        }
        let name = getWarehouseName(data.value);
        $("#warehouseName").val(name);
        let oldTransferData =  table.cache["productinformationtableid"];
        if(oldTransferData.length > 0){
            for(let i in oldTransferData){
                oldTransferData[i]["warehouseName"] = name;
                oldTransferData[i]["warehouseId"] = data.value;
            }
            table.reload('productinformationtableid',{data : oldTransferData});
        }else {
            return;
        }
    })


    function getWarehouseName(code){
        for(let i in warehouseList){
            if(warehouseList[i].code == code){
                return warehouseList[i].name;
            }
        }
        return "";
    }



    //表单初始值
    if (id != "") {
        ids = id.split(",");//id为多个数组存储
        form.val("editor-form", {
            "receiptnumber": "单据编号",
        })
    }

    //监听提交
    form.on('submit(form-element)', function (data) {
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        //获取表单信息数据
        let detail = table.cache["productinformationtableid"];
        if(detail.length > 0){
            for(let i in detail){
                let num = parseInt(i) + 1;
                //字段校验
                if(!checkData(detail[i], num)){
                    return false;
                }

            }
        }

        req["details"] = detail;
        let datas = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"resourceSamples/add/register",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/WarehouseManagement/samplesresources.jsp");
                        parent.intab("views/jsp/WarehouseManagement/samplesresources.jsp", "工厂仓库");
                        parent.detab("views/jsp/WarehouseManagement/tpl/ResourceSamplesTakeOutUpdate.jsp" + (id == '' ? '' : '?id=' + id));
                    }, 1000);
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
                return false;
            }
        });
    });

    function checkData(data, i) {
        if(isEmpty(data.warehouseName)){
            layer.msg("第"+ i +"行：仓库名称不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.productNum)){
            layer.msg("第"+ i +"行：数量不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.productUnit)){
            layer.msg("第"+ i +"行：单位不能为空，请产品维护", {icon: 5});
            return false;
        }
        if(isEmpty(data.articleNo)){
            layer.msg("第"+ i +"行：货位不能为空", {icon: 5});
            return false;
        }

        return true;
    }

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }

    //--入库产品信息
    let initData = [];
    table.render({
        elem: '#productinformation',
        id: 'productinformationtableid',
        data: initData,
        toolbar: '#productinformationtoolbar',
        cols: [[
            {checkbox: true, fixed: true},
            {field: 'img', title: '产品图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'productCode', width: 220, title: '产品编码', templet: '#productcodeselect'},
            {field: 'specificationCode', width: 120, title: '规格编码', edit: 'text'},
            {field: 'productCname', width: 120, title: '中文名称', edit: 'text'},
            {field: 'productEname', width: 120, title: '英文名称', edit: 'text'},
            {field: 'productCdesc', width: 120, title: '中文描述', edit: 'text'},
            {field: 'productEdesc', width: 120, title: '英文描述', edit: 'text'},
            {field: 'unitPrice', width: 120, title: '单价', edit: 'text'},
            {field: 'productNum', width: 120, title: '数量', edit: 'text'},
            {field: 'productUnit', width: 120, title: '单位'},
            {field: 'articleNo', width: 120, title: '货位', templet: '#articleNoSelect'},
            {field: 'supplierCode', title: '供应商', width: 240, templet: '#materialSupplierSelect'},
            {field: 'lotNo', width: 180, title: '批次号'},
            {field: 'warehouseId', width: 160, title: '资源样品仓库', templet: '#resourcesamplewarehouse'},
            {field: 'specificationExplanation', width: 120, title: '备注', edit: 'text'},
        ]],
        page: true,
        height: 380
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            hoverOpenImg();//显示大图
            for(let i in warehouseList){
                $(".warehouse").append("<option value=\"" + warehouseList[i].code + "\">" + warehouseList[i].name + "</option>");
            }
            for(let i in articleNoList){
                $(".articleNo").append("<option value=\"" + articleNoList[i].name + "\">" + articleNoList[i].name + "</option>");
            }
            //供应商
            for(let i in materialSupplierList){
                $(".supplierCode").append("<option value=\"" + materialSupplierList[i].code + "\">" + materialSupplierList[i].name + "</option>");
            }
            for (var i = 0; i < res.data.length; i++) {
                let tempId = res.data[i].tempId;
                $("#warehouse_" + tempId).val(res.data[i].warehouseId);
                $("#articleNo_" + tempId).val(res.data[i].articleNo);
                $("#supplierCode_" + tempId).val(res.data[i].supplierCode);
            }
            form.render('select');
        }
    });

    form.on("select(articleNoSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["productinformationtableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["articleNo"] = data.value;
            }
        });
    });

    //监听供应商下拉框
    form.on("select(materialSupplierSelect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataindex = elem.attr("data-index");
        let tabledata = table.cache["productinformationtableid"];
        $.each(tabledata, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataindex) {
                tabledata[index]["supplierCode"] = data.value;
                tabledata[index]["supplierName"] = getMaterialSupplierName(data.value);
            }
        });
    });
    function getMaterialSupplierName(code){
        for(let i in materialSupplierList){
            if(materialSupplierList[i].code == code){
                return materialSupplierList[i].name;
            }
        }
        return "";
    }

    form.on("select(resourcesamplewarehouse_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["productinformationtableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["warehouseId"] = data.value;
                tableData[index]["warehouseName"] = getWarehouseName(data.value);
            }
        });
    });

    function getWarehouseName(code){
        for(let i in warehouseList){
            if(warehouseList[i].code == code){
                return warehouseList[i].name;
            }
        }
        return "";
    }

    function hoverOpenImg() {
        // tips提示
        let img_show = null;
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

    table.on('edit(productinformationtable)', function (obj) {
        //旧值
        let old = $(this).prev().text();
        //判断数据类型
        if ((obj.field == "unitPrice" || obj.field == "productNum") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
    });

    function isNumber(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }

    table.on('toolbar(productinformationtable)', function (obj) {
        let checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'resourcesamplelibrary':
                layer.open({
                    type: 2,
                    area: $(window).width() < 458 ? "['100%', '100%']" : ['80%', '95%'],
                    content: 'views/jsp/WarehouseManagement/tpl/resourcesamplelibrary.jsp'
                });
                break;
            case 'del':
                let data = checkStatus.data, delList = [];
                data.forEach(function (n, i) {
                    delList.push(n.tempId);
                });
                if (delList != '') {
                    layer.confirm('确定删除所选项吗？', confirmInfo(3,5), function (index) {
                        let cbList = table.cache["productinformationtableid"];
                        for (var i = 0; i < cbList.length; i++) {
                            delList.forEach((item, index) => {
                                //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                                if (typeof (cbList[i]) != "undefined" && item == cbList[i].tempId) {
                                    cbList.splice(i, 1);
                                }
                            })
                        }
                        table.reload("productinformationtableid", {
                            data: cbList,
                        })
                        layer.msg('删除成功');
                    })
                } else {
                    layer.msg('请选择需要删除的行');
                }
                break;
        };
    });

    //时间处理 获取当前时间type:1 yyyy-MM-dd type:2 yyyyMMdd+毫秒
    function getNowFormatDate(type) {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if(1 == type){
            let currentDate = year + separator + month + separator + strDate;
            return currentDate;
        }else if(2 == type){
            let second = date.getMilliseconds().toString();
            if(second.length < 3){
                if(second.length == 1){
                    second = "0" + "0" + second;
                }else {
                    second = "0" + second;
                }
            }
            let currentDate = year.toString() + month.toString() + strDate.toString() + second;
            return currentDate;
        }

    }

    let currentDate = getNowFormatDate(1);
    //创建时间
    layui.laydate.render({
        elem: '#createDate',
        value: currentDate,
        min: currentDate,
        max: currentDate,
        btns: ['confirm']
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }


    //生成临时id
    function GenNonDuplicateID(randomLength){
        return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
    }
});

